import { useState, useEffect } from "react"
import { message } from "antd"

import Item from "./Item"

import http from "../../request"
import { torem } from "../../assets/js/rem"

const Screen = (props) => {
  const [screenData, setScreenData] = useState([])
  const [list, setList] = useState([])
  const [pager, setPager] = useState({limit: 20, offset: 0})
  const [scrollTop, setScrollTop] = useState(0)
  const [shaking, setShaking] = useState(!1)

  useEffect(() => {
    getScreen()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return(
    <div className="u-m-b-50" style={{height:'85vh',overflow:'scroll'}} onScroll={scroll}>
      {list.map(i => <div key={i}><div className="u-p-l-10" style={{lineHeight:torem(32),backgroundColor:'rgb(245,247,250)'}}>{i}</div>{screenData.map(t => t.openTime === i ? <Item key={t.id} data={t} type='Screen' setVideo={props.video}/> : '')}</div>)}
    </div>
  )
  function getScreen() {
    http('/coming/', 'get', {params:{...pager}}).then(res => {
      if(res.data.data.returnCode === '0') {
        console.log(res);
        setScreenData([...screenData, ...res.data.data.returnValue])
        const da = [...screenData, ...res.data.data.returnValue].map(i => i.openTime)
        const time = new Set(da)
        setList(Array.from(time))
        const page = JSON.parse(JSON.stringify(pager))
        page.offset = page.offset + page.limit
        setScrollTop(page.offset * 100 - 500)
        setPager(page)
        if (pager.offset >= res.total) {
          message.open({
            type: 'success',
            content: '加载完毕',
          });
        }
      }
    }).catch(err => console.log(err))
  }
  function scroll(e) {
    if(shaking) return
    
    setShaking(!0)
    if(e.target.scrollTop >= scrollTop) {
      getScreen()
    }
    setTimeout(() => {
      setShaking(!1)
    }, 500);
    
  }
}

export default Screen